﻿Imports System.Drawing

Public Class MemberDetail
    Inherits ItemDetailPage

    Protected Property PhotoNormalSize() As New Size() With {.width = 128, .height = 128}
    Protected Property PhotoThumbSize() As New Size() With {.width = 64, .height = 64}
    Protected Property UserName() As String

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        UserName = Request.QueryString.Get("UserName")
        If Not IsPostBack Then
            If Not String.IsNullOrWhiteSpace(UserName) AndAlso UserExists(UserName) Then
                Select Case Request.QueryString.Get("Action")
                    Case "Edit"
                        DetailFormView.DefaultMode = FormViewMode.Edit
                End Select
                UpdateDataSource()
            Else
                Response.Redirect("~/Pages/MemberList.aspx")
            End If
        End If
    End Sub

    Protected Sub SaveButton_Click(sender As Object, e As EventArgs)
        Dim gateway As New SiteUserGateway()
        Dim firstName As TextBox = DetailFormView.FindControl("FirstNameTextBox")
        Dim lastName As TextBox = DetailFormView.FindControl("LastNameTextBox")
        Dim photo As FileUpload = DetailFormView.FindControl("PhotoFileUpload")

        If photo.HasFile() Then
            Dim fileName As String = PhotoUtils.getUniqueFileName(photo.FileName)
            PhotoUtils.Save(fileName, photo.PostedFile.InputStream, PhotoNormalSize, PhotoThumbSize)
            gateway.Update(UserName, firstName.Text, lastName.Text, fileName)
        Else
            gateway.Update(UserName, firstName.Text, lastName.Text)
        End If

        StopEditing()
    End Sub

    Protected Sub CancelEditButton_Click(sender As Object, e As EventArgs)
        StopEditing()
    End Sub

    Protected Sub EditButton_Click(sender As Object, e As EventArgs)
        StartEditing()
    End Sub

    Protected Function UserExists(ByVal userName As String) As Boolean
        Dim gateway As New SiteUserGateway()
        Return gateway.Exists(userName)
    End Function

    Protected Sub StartEditing()
        Dim redirectUrl As String = String.Format("~/Pages/MemberDetail.aspx?UserName={0}&Action=Edit", UserName)
        Response.Redirect(redirectUrl)
    End Sub

    Protected Sub StopEditing()
        Dim redirectUrl As String = String.Format("~/Pages/MemberDetail.aspx?UserName={0}", UserName)
        Response.Redirect(redirectUrl)
    End Sub

    Protected Function getPhotoPath(ByVal fileName As String) As String
        Return PhotoUtils.getNormalPath(fileName)
    End Function

    Protected Sub UpdateDataSource()
        Dim gateway As New SiteUserGateway()
        DetailFormView.DataSource = gateway.FindByUserName(Request.QueryString.Get("UserName"))
        DetailFormView.DataBind()
    End Sub
End Class